// https://blog.csdn.net/joy1793/article/details/109165921
console.log("contentScript.js")

function addJs(url) {
    let script = document.createElement("script");
    script.src = chrome.runtime.getURL(url);
    script.setAttribute("type", "text/javascript");
    document.head.appendChild(script);
}

function injectMonitor() {
    const injectScript = (file, node) => {
        const th = document.querySelector(node);
        const s = document.createElement('script');
        s.setAttribute('type', 'text/javascript');
        s.setAttribute('src', file);
        th.appendChild(s);
      };
      injectScript( chrome.runtime.getURL('/design/monitors.js'), 'body');
}

let showCard = true;

function onLoaded() {
    let funcTab = document.getElementsByClassName("operation-tab");
    if (funcTab.length > 0) {
        console.log("onLoaded check: " + funcTab.length + ", child: " + funcTab[0].children.length);

        let div = '<div id="switch_panel" class="tab-name"><span style="color: #0093ff">切换</span></div>';
        $(".operation-tab").append(div);

        $("#switch_panel").on("click", function() {
            if (showCard) {
                disable = true;
                clearSelected();
                $("#show_info_view_bg").css("visibility", "hidden");
            } else {
                disable = false;
                $("#show_info_view_bg").css("visibility", "visible");
            }
            showCard = !showCard
        });
    } else {
        console.log("onLoaded check: wait again");
        setTimeout(onLoaded, 100);
    }
}

function initMonitors() {
    console.log('content script start');

    // receive message from injected script
    window.addEventListener('message', function (e) { 
        let data = e.data;
        if (data.type == 'xhr') {
            let url = data.url;
            // https://alipic.lanhuapp.com/SketchJSONURL204cc4dba903b136e59dfcf48827f397707456c7138d77316d7e4c4a8ef04eed
            if (url.includes('SketchJSONURL')) {
                console.log('xhr SketchJSONURL data:', data.data);
            }
        } else if (data.type == "levelMapToArray") {
            // let result = I(data.data);
            let result = data.data;
            if (!data.isSketch) {
                result = fixPsData(result);
            }
            console.log("receive origin data", data.data.length, result.length);
            originData = result;

            onLoaded();
            inspect();
            intercept();
        }
        // console.log('content script received:' , e.data.type, e.data.data);
    });
}

function initPage() {
    initMonitors();
    injectMonitor();
}

window.onload = initPage;